<template>
  <div class="knowledge-explorer">
    <div class="page-header">
      <h1>知识查询</h1>
      <p class="subtitle">智能问答与知识检索系统</p>
    </div>

      <el-row :gutter="30" class="mb-4">
        <el-col :span="16">
          <el-card class="query-section">
            <div class="query-input">
              <el-input
                v-model="query"
                type="textarea"
                :rows="4"
                placeholder="请输入您的问题，例如：细胞呼吸是什么？"
                resize="none"
              />
              <el-button type="primary" :loading="loading" @click="handleQuery" class="query-button">
                <el-icon><Search /></el-icon>
                开始查询
              </el-button>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card class="suggestions-section">
            <template #header>
              <h2 style="display: inline-block">热门问题</h2>
              <el-button style="float: right;background-color: #6aaff6;">
                <el-icon @click="refreshSearch()" size="20" style="color: white;"><Refresh /></el-icon>
              </el-button>

            </template>
            <div class="suggestion-list">
              <div
                v-for="suggestion in suggestions"
                :key="suggestion.id"
                class="suggestion-item"
                @click="useQuery(suggestion.query)">
                <el-icon><QuestionFilled /></el-icon>
                <span>{{ suggestion.search_content }}</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="30">
        <el-col :span="16">
          <el-card v-if="answer" class="answer-section">
            <h3>查询结果</h3>
            <div class="answer-content">
              <el-alert
                :title="answer.summary"
                type="success"
                :closable="false"
                class="answer-summary"
              />
              <div class="answer-detail" v-html="answer.detail">

              </div>
              <div v-if="answer.sources && answer.sources.length" class="answer-sources">
                <h4>参考来源：</h4>
                <el-tag
                  v-for="source in answer.sources"
                  :key="source.id"
                  class="source-tag"
                  @click="viewSource(source)">
                  {{ source.name }}
                </el-tag>
              </div>
            </div>
          </el-card>

          <el-card class="history-section">
            <template #header>
              <div class="card-header">
                <h3>历史查询</h3>
                <el-button text @click="clearHistory">
                  清空历史
                </el-button>
              </div>
            </template>

            <div class="history-content">
              <el-timeline>
                <el-timeline-item
                  v-for="item in queryHistory"
                  :key="item.id"
                  :timestamp="item.time"
                  placement="top">
                  <div class="history-item">
                    <el-alert
                      :title="item.query"
                      type="info"
                      :closable="false"
                      class="history-query"
                    />
                    <div class="history-answer-content">
                      {{ item.answer }}
                    </div>
                    <div class="history-actions">
                      <el-button link type="primary" @click="reuse(item)">重新查询</el-button>
                      <el-button link type="danger" @click="removeFromHistory(item)">删除</el-button>
                    </div>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-card>
        </el-col>

        <el-col :span="8">
          <el-card class="stats-section">
            <template #header>
              <h2>知识统计</h2>
            </template>
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="stat-item">
                  <div class="stat-value">{{ stats.totalNodes }}</div>
                  <div class="stat-label">实体总数</div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="stat-item">
                  <div class="stat-value">{{ stats.totalRelationships }}</div>
                  <div class="stat-label">关系总数</div>
                </div>
              </el-col>
            </el-row>
            <el-divider />
            <h3>实体类型分布</h3>
            <div class="query-distribution">
              <el-progress
                v-for="(count, label) in queryDistribution"
                :key="label"
                :percentage="count"
                :format="formatPercentage"
                :stroke-width="15"
                class="distribution-item">
                {{ label }}
              </el-progress>
            </div>
          </el-card>
        </el-col>
      </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { Search, QuestionFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { marked } from 'marked';
const query = ref('')
const loading = ref(false)
const answer = ref({
  summary: '',
  detail: '',
  sources: []
})

// 查询历史
const queryHistory = ref([])
const loadingHistory = ref(false)

// 统计信息
const stats = ref({
  nodesByLabel: [],
  totalNodes: 0,
  totalRelationships: 0,
  nodeTypes: [],
  relationTypes: [],
  totalQueries: 0,
  avgResponseTime: 0
})

// 计算查询类型分布
const queryDistribution = computed(() => {
  const total = stats.value.totalNodes || 1

  // 初始化分布对象，包含所有标签
  const distribution = {
    '生活': 0,
    '人文': 0,
    '科技': 0,
    '军事': 0
  };

// 计算每个标签的百分比
  stats.value.nodesByLabel.forEach(item => {
    if (item.label in distribution) {
      distribution[item.label] = Number(((item.count / total) * 100).toFixed(2));
    }
  });

  console.log('分类',distribution)
  console.log('类型',total)
  return distribution
})

// 热门问题建议
const suggestions = ref([
  { id: 1, query: '羽绒棉的主要特性是什么？' },
  { id: 2, query: '羽绒棉与传统棉花的区别？' },
  { id: 3, query: '羽绒棉的应用场景有哪些？' },
  { id: 4, query: '羽绒棉的生产工艺流程是怎样的？' },
  { id: 5, query: '羽绒棉的保养方法有哪些？' }
])

// 格式化进度条显示
const formatPercentage = (percentage) => {
  return `${percentage}%`
}

// 格式化答案内容
const formatAnswer = (text) => {
  if (!text) return ''
  // 将文本按段落分割
  const paragraphs = text.split('\n').filter(p => p.trim())
  // 如果只有一段，直接返回
  if (paragraphs.length <= 1) return text
  
  // 如果有多段，添加序号
  return paragraphs.map((p, index) => `${index + 1}. ${p.trim()}`).join('\n\n')
}

// 处理知识查询
const handleQuery = async () => {
  if (!query.value) {
    ElMessage.warning('请输入问题')
    return
  }
  
  loading.value = true
  let retryCount = 0
  const maxRetries = 1
  const timeoutDuration = 30000 // Increase timeout to 30 seconds

  const attemptQuery = async () => {
    try {
      const response = await axios.post('/api/knowledge/query', {
        question: query.value
      }, {
        timeout: timeoutDuration,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      
      if (response.data.code === 200) {
        // 更新答案显示
        answer.value = {
          summary: '查询结果',
          detail: formatAnswer(response.data.data),
          sources: []
        }
        answer.value.detail = marked(response.data.data);
        // 添加到查询历史
        const queryTime = new Date().toLocaleString()
        queryHistory.value.unshift({
          id: Date.now(),
          query: query.value,
          answer: formatAnswer(response.data.data),
          time: queryTime
        })
        
        // 保持最近10条记录
        if (queryHistory.value.length > 10) {
          queryHistory.value.pop()
        }
        
        // 更新统计信息
        loadStats()
        
        // 清空查询输入框
        query.value = ''
        
        ElMessage.success('查询成功')
      } else {
        throw new Error(response.data.message || '查询失败')
      }
    } catch (error) {
      console.error('查询失败：', error)
      
      if (retryCount < maxRetries && (error.code === 'ECONNABORTED' || error.message.includes('timeout'))) {
        retryCount++
        ElMessage.warning(`查询超时，正在进行第${retryCount}次重试...`)
        return attemptQuery()
      }
      
      if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
        ElMessage.error('查询超时，请检查网络连接或稍后重试')
      } else {
        ElMessage.error(error.message || '查询失败，请检查网络连接')
      }
    }
  }

  try {
    await attemptQuery()
  } finally {
    loading.value = false
  }
}

// 加载统计信息
const loadStats = async () => {
  try {
    const response = await axios.get('/api/knowledge/stats')
    if (response.data.code === 200) {
      stats.value = response.data.data
      console.log('统计节点',stats.value)
    } else {
      ElMessage.error(response.data.message || '获取统计信息失败')
    }
  } catch (error) {
    console.error('获取统计信息失败：', error)
    ElMessage.error('获取统计信息失败，请检查网络连接')
  }
}
//刷新大家在问
const refreshSearch = async() => {
  await getOtherSearch()
}
//加载大家都在问的问题
const getOtherSearch = async() =>{
  try {
    const { data } = await axios.get('/api/allSearchList/other',{
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
      },
    })
    console.log('大家在问',data)
    suggestions.value = data.data
  } catch (e) {
    await Promise.reject(e)
  }
}

// 使用建议的查询
const useQuery = (suggestionQuery) => {
  query.value = suggestionQuery
  handleQuery()
}

// 查看来源文档
const viewSource = (source) => {
  window.open(`${axios.defaults.baseURL}/api/documents/${source.name}`, '_blank')
}

// 清空历史记录
const clearHistory = () => {
  queryHistory.value = []
  ElMessage.success('历史记录已清空')
}

// 重用历史查询
const reuse = (item) => {
  query.value = item.query
  handleQuery()
}

// 从历史记录中删除
const removeFromHistory = (item) => {
  queryHistory.value = queryHistory.value.filter(i => i.id !== item.id)
  ElMessage.success('已从历史记录中删除')
}

// 组件挂载时加载数据
onMounted(() => {
  loadStats()
  getOtherSearch()
})
</script>

<style scoped>
html, body {
  height: 100vh;
  width: 100vw;
  margin: 0;
  padding: 0;
  overflow-x: hidden;
}
.knowledge-explorer {
  padding: 40px;
  max-width: 100vw;
  margin: 0 auto;
  height: calc(100vh);
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #409EFF 0%, #36D1DC 100%);
  margin: 0;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.page-header {
  margin-bottom: 40px;
  margin-top: 20px;
  flex-shrink: 0;
  text-align: left;
  color: white;
}

.page-header h1 {
  font-size: 36px;
  font-weight: 600;
  margin-bottom: 16px;
  color: white;
}
.page-title {
  font-size: 36px;
  font-weight: 600;
  margin-bottom: 30px;
  color: white;
}

.subtitle {
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
  margin-bottom: 40px;
}

.page-content {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  flex: 1;
  min-height: 0;
}

.query-section {
  background: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

.query-input {
  display: flex;
  flex-direction: column;
  gap: 15px;
  padding: 20px;
}

.query-button {
  width: 120px;
  margin-left: auto;
}

.answer-section {
  margin-bottom: 20px;
}

.answer-content {
  padding: 20px;
}

.answer-detail {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  line-height: 1.8;
  color: #2c3e50;
  font-size: 15px;
  overflow-wrap: break-word;
  word-wrap: break-word;
  margin: 20px 0;
}

:deep(.el-card__body) {
  padding: 0px !important;
}

.query-section :deep(.el-card__body) {
  padding: 20px !important;
}

.suggestions-section :deep(.el-card__body),
.stats-section :deep(.el-card__body) {
  padding: var(--el-card-padding) !important;
}

.answer-section :deep(.el-card__body) {
  padding: 20px !important;
}

.answer-detail p {
  margin-bottom: 12px;
}

.answer-sources {
  margin-top: 20px;
}

.answer-sources h4 {
  color: #2c3e50;
  margin-bottom: 10px;
}

.source-tag {
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer;
}

.history-section {
  margin-top: 20px;
  border-radius: 8px;
  background: white;
}

.history-section :deep(.el-card__body) {
  padding: 20px !important;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
}

.history-content {
  padding: 0 20px;
}

.history-item {
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.history-query {
  margin-bottom: 15px;
}

.history-answer-content {
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  line-height: 1.8;
  color: #2c3e50;
  font-size: 15px;
  overflow-wrap: break-word;
  word-wrap: break-word;
  margin: 15px 0;
}

.history-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 15px;
}

/* 移除旧的历史记录相关样式 */
.history-item h4,
.history-answer {
  display: none;
}

.suggestions-section {
  margin-bottom: 30px;
}

.suggestion-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.suggestion-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.suggestion-item:hover {
  background: #e9ecef;
}

.suggestion-item .el-icon {
  color: #409EFF;
}

.stats-section {
  margin-bottom: 30px;
}

.stat-item {
  text-align: center;
  padding: 15px;
}

.stat-value {
  font-size: 1.8em;
  color: #409EFF;
  font-weight: bold;
}

.stat-label {
  color: #666;
  margin-top: 5px;
}

.query-distribution {
  margin-top: 20px;
}

.distribution-item {
  margin-bottom: 15px;
}

@media (max-width: 768px) {
  .knowledge-explorer {
    padding: 20px;
  }
  
  .query-button {
    width: 100%;
  }
  
  .source-tag {
    margin-bottom: 8px;
  }
}
</style> 